package com.thomas.generator.util;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Map;

/**
 * @author xutao
 * @Package com.thomas.generator.util
 * @Description: ${todo}
 * @date 2019/12/11 9:51
 */
public class FreemarkerUtil {

    private String moduleName=PropertiesUtil.get("project.moduleName");
    public static String path = System.getProperty("user.dir");

    public Template getTemplate(String name) {
        try {
            Configuration cfg = new Configuration();
            cfg.setDefaultEncoding("GBK");
//			cfg.setClassForTemplateLoading(this.getClass(),"/template");
            cfg.setClassForTemplateLoading(this.getClass(),"/template");
            Template temp = cfg.getTemplate(name);
            return temp;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public void generator(String templateName, Map<String,Object> root, String outFile) {
        FileWriter out = null;
        try {
            String distPath = path+"/dist/"+outFile;
            if(templateName.contains("IService")){
                distPath = path+"/dist/"+moduleName+"/service/"+outFile;
            }else if(templateName.contains("ServiceImpl")){
                distPath = path+"/dist/"+moduleName+"/service/impl/"+outFile;
            }else if(templateName.contains("Controller")){
                distPath = path+"/dist/"+moduleName+"/web/"+outFile;
            }else if(templateName.contains("Dao")){
                distPath = path+"/dist/"+moduleName+"/dao/"+outFile;
            }else if(templateName.contains("Mapper")){
                distPath = path+"/dist/mapping/"+moduleName+"/"+outFile;
            }else if(templateName.contains("Model")){
                distPath = path+"/dist/"+moduleName+"/model/"+outFile;
            }else if(templateName.contains("JspMgr")){
                distPath = path+"/dist/"+moduleName+"/jsp/"+outFile;
            }
            File distFile = new File(distPath);
            if(!distFile.exists()){
                if(!distFile.getParentFile().exists())
                    distFile.getParentFile().mkdirs();
                distFile.createNewFile();
            }
            out = new FileWriter(distFile);
            Template temp = this.getTemplate(templateName);
            temp.process(root, out);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TemplateException e) {
            e.printStackTrace();
        } finally {
            try {
                if(out!=null) out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
